package controllers;

import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.UserModel;

import entities.User;
import forms.UserForm;

public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TreeMap check = new TreeMap();
		User user = new User();				
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/demo/pages/form_login.jsp").forward(request,
					response);
		} catch (ServletException e) {

		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		HttpSession session = request.getSession();
		TreeMap check = new TreeMap();
		
		UserModel userModel = UserModel.getInstance();
		User user = new User();
		
		TreeMap form = UserForm.checkLogin(request, user);
		user = (User) form.get("user");
		check = (TreeMap) form.get("checkValid");
		
		String returnUrl = (String) request.getParameter("returnUrl");
		
		if (check.size() == 0) {
			User user_login = userModel.getByUsername(user.getUsername());
			if (user_login != null) {
				if (user_login.getPassword().equalsIgnoreCase(
						StringHelper.md5(user.getPassword()))) {
					if (user_login.getStatus() == 2) {
						// Save login to session
						session.setAttribute("user_logged_in", user_login);
						if (returnUrl != null && returnUrl.length() > 0) {
							response.sendRedirect("/" + returnUrl);
							return;
						} else {
							response.sendRedirect("/");
							return;
						}
		
					} else {
						check.put("username", "Account has not been active!.");
					}
				} else {
					check.put("password", "Incorrect password!");
				}
			} else {
				check.put("username", "Username not exists.");
			}
		}
		
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/demo/pages/form_login.jsp").forward(request,
					response);
		} catch (ServletException e) {
			// e.printStackTrace();
		}
	}
}
